package com.ccctop.crowd.service.Impl;

import com.ccctop.crowd.api.MySQLRemoteService;
import com.ccctop.crowd.entity.po.ProjectPO;
import com.ccctop.crowd.entity.po.TFundRequestInfo;
import com.ccctop.crowd.entity.vo.MyCreateProjectVo;
import com.ccctop.crowd.service.ProjectConsumerService;
import com.ccctop.crowd.util.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProjectConsumerServiceImpl implements ProjectConsumerService {
    @Autowired
    private MySQLRemoteService mySQLRemoteService;
    @Override
    public List<MyCreateProjectVo> getMyCreateProject(Integer memberLoginVOId) throws Exception {
        ResultEntity<List<ProjectPO>> myProjects = mySQLRemoteService.getProjectsByMemberId(memberLoginVOId);
        return getVos(myProjects);
    }

    private List<MyCreateProjectVo> getVos(ResultEntity<List<ProjectPO>> myProjects) throws Exception {
        if (myProjects.getResult().equals(ResultEntity.SUCCESS)){
            List<MyCreateProjectVo> collect = myProjects.getData().stream().map((item) -> {
                MyCreateProjectVo vo = new MyCreateProjectVo();
                BeanUtils.copyProperties(item, vo);
                //TODO 这里应该采用直接从project里查进度，而不是直接计算
                vo.setCompletion(item.getSupportmoney()/(double)item.getMoney());
                vo.setDeploydate(new SimpleDateFormat("yyyy-MM-dd").format(item.getDeploydate()));
                //查询跟该项目有关的资金提取请求,只返回状态为请求中-0的状态
                ResultEntity<TFundRequestInfo> infoResultEntity = mySQLRemoteService.selectFundRequestInfoByProjectId(item.getId());
                if (infoResultEntity.getResult().equals(ResultEntity.SUCCESS)){
                    TFundRequestInfo requestInfo = infoResultEntity.getData();
                    if (requestInfo!=null){
                        vo.setFundRequestInfoStatus(requestInfo.getStatus());
                    }else {
                        vo.setFundRequestInfoStatus(null);
                    }
                }
                return vo;
            }).collect(Collectors.toList());
            return collect;
        }else {
            throw new Exception(myProjects.getMessage());
        }
    }

    @Override
    public List<MyCreateProjectVo> queryMySupportProject(Integer userId) throws Exception {
        ResultEntity<List<ProjectPO>> myProjects = mySQLRemoteService.getSupportProjectsByMemberId(userId);
        return getVos(myProjects);
    }
}
